<template>
  <el-dialog title="编辑" :close-on-click-modal="false"  :visible.sync="show"  class="dialog_index" :before-close="cancle">
    <el-form   label="right" :rules="rules" :model="form" ref="editForm" v-loading="loading" >
      <el-form-item label="图标：" props="icon" :class="!form.icon ?'menuIcon isnoIcon':'menuIcon'">
        <el-upload class="uploadLangIcon" :action="actionUrl" :multiple="false"
          :show-file-list="false" accept=".jpg,.jpeg,.png " :data="{type:'site'}"
          :on-success="handleLangSuccess" :on-error="handleLangError"
          :before-upload="beforeLangUpload">
         <p >
            <img :src="utils.setCdnUrl()+form.icon" v-if="form.icon" class="iconSite">
            <span v-else> <i class="el-icon-plus"></i></span>
            <SvgIcon iconClass="icon-upload" className="icon_upload"></SvgIcon>
          </p>
          <div class="el-upload__tip" slot="tip">仅支持jpg/jpeg格式，且尺寸为1:1，大小≤500KB</div>
        </el-upload>
      </el-form-item>
      <el-form-item label="国家中文名称：" prop="name_cn">
        <el-input v-model="form.name_cn" placeholder="国家中文名称（必填项）"></el-input>
      </el-form-item>
       <el-form-item label="国家英文名称：" prop="name_en">
        <el-input v-model="form.name_en" placeholder="国家英文名称（必填项）"></el-input>
      </el-form-item>
       <el-form-item label="站点：" prop="site">
        <el-input v-model="form.site" placeholder="站点（必填项）"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button type="search" @click="submitForm">保存</el-button>
      <el-button @click="cancle">取消</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { siteEditPost, siteEditGet } from '@/api/manage/site.js'
import SvgIcon from '@/components/SvgIcon'

export default {
  props: {
    show: Boolean,
    closeEditDialog:Function,
    id: Number
  },
  components: { SvgIcon },

  data() {
    return {
      form:{
        name_cn: "",
        icon: "",
        name_en: '',
        site: '',
        status: 1
      },
      img: "",
      // 字段xx为必填项！
      rules:{
        name_cn:[
          { required: true, message: '字段国家中文名称为必填项', trigger: 'change' },
          { min: 1, max: 20, message: '国家中文名称最多20字符', trigger: 'blur' }
        ],
        name_en:[
          { required: true, message: '字段国家英文名称为必填项', trigger: 'change' },
            { min: 1, max: 50, message: '国家英文名称最多50字符', trigger: 'blur' }
        ],
        site:[
          { required: true, message: '字段站点为必填项', trigger: 'change' },
            { min: 1, max: 2, message: '站点最多2字符', trigger: 'blur' }
        ],
        icon: [
          { required: true, message: '图标为必填项', trigger: 'blur' },
        ]
      },
      actionUrl: "/api/api/general/upload",
      loading: false
    }
  },
  watch:{
    show: function(){
      if (this.show) {
        this.getSiteEdit()
      }
    }
  },
  mounted(){
  },
  methods:{

    submitForm(){
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.postSiteEdit()
        } else {
          return false;
        }
      });
    },
    getSiteEdit(){
      this.loading = true
      let params = {
        id: this.id
      }
      siteEditGet(params).then(res=>{
        console.log(res)
        if(res.state == 1) {
          this.form = res.data
          this.img = res.data.iconhttp
        } else {
          this.$message.error(res.message)
        }
         this.loading = false
      })
    },
    postSiteEdit(){
      siteEditPost(this.form).then(res=>{
       console.log(res)
       if(res.state == 1){
        this.$message.success('保存站点信息' +res.message)
        this.cancle()
       }
      })
    },
    cancle(){
      this.$emit('closeDialog')
      this.$refs.editForm.clearValidate();
    },
    handleLangSuccess(response, file, fileList){
      console.log(response, file, fileList)
      this.form.icon = response.data.filePathName
      this.img = response.data.filePathNameHttp 
      this.$message.success('上传图标成功')   
    },
    handleLangError(){
      this.$message.error('上传图标失败')   
    },
    beforeLangUpload(file){
      let that = this
      const isLt2M = file.size / 1024  <  500;
      if(!isLt2M){
        this.$message.error("上传图片大小不超过500KB")
        return false
      }
      if(file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/jpg'){
        this.$message.error("仅支持.jpg/.jpeg/png格式的图片")
        return false
      }
      const isSize = new Promise(function(resolve, reject){
        let _URL = window.URL || window.webkitURL;
        let img = new Image();
        img.onload = function() {
          console.log(img.width,img.height)
          let valid = img.width ==  img.height ;
          valid ? resolve() : reject();
        }
        img.src = _URL.createObjectURL(file);
      }).then(()=>{

        return file
      }, ()=>{
        that.$message.error('上传图标为正方形')
        return Promise.reject()
      })
      return isSize
    }
  }
}
</script>

<style lang="scss">

</style>